package com.itheima.stock.service.Impl;


import com.itheima.stock.cache.Cache;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import com.itheima.stock.constant.Constant ;

/**
 * UserServiceImpl
 *
 * @author DanLi
 * @date 2025/7/13
 */
@Service
public class UserServiceImpl implements UserService {


    //定义随机数的位数
    private static final int CAPTCHA_LENGTH = 4;
    private final IdWorkers idWorkers;
    private final Cache cache;

    public UserServiceImpl(IdWorkers idWorkers, Cache cache) {
        this.idWorkers = idWorkers;
        this.cache = cache;
    }


    /**
     * 获取验证码
     *
     * @return {@link CaptchaVO}
     */
    @Override
    public CaptchaVO Captcha() {
        //1.生成验证码
        String code = RandomStringUtils.randomNumeric(CAPTCHA_LENGTH);
        //2,将验证码存入redis中
        //2.1 生成redis_key
        String key = RedisKeyUtil.generateKey(Constant.USER_CAPTCHA_PREFIX, idWorkers.nextStrId());
        //2.2 存入redis中
        cache.set(key, code, Constant.USER_CAPTCHA_EXPIRE_TIME);
        //3.返回验证码
        return CaptchaVO.builder()
                .code(code)
                .rkey(key)
                .build();
    }
}
